import 'dart:async';
import 'dart:io';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'log.dart';



/// 将标签 color 转为 颜色
Color HexString(String color, {double alpha = 1}) {
  var hex = int.parse("0xFF${color.substring(1)}");
  if (alpha < 0) {
    alpha = 0;
  } else if (alpha > 1) {
    alpha = 1;
  }
  return Color.fromRGBO((hex & 0xFF0000) >> 16, (hex & 0x00FF00) >> 8,
      (hex & 0x0000FF) >> 0, alpha);
}

/// 十六进制颜色，
/// hex, 十六进制值，例如：0xffffff,
/// alpha, 透明度 [0.0,1.0]
Color hexColor(int hex, {double alpha = 1}) {
  if (alpha < 0) {
    alpha = 0;
  } else if (alpha > 1) {
    alpha = 1;
  }
  return Color.fromRGBO((hex & 0xFF0000) >> 16, (hex & 0x00FF00) >> 8,
      (hex & 0x0000FF) >> 0, alpha);
}

/// 延迟调用
/*
hkSetTimeout(() {
  //xxx
}, Duration(milliseconds: 500));
 */
void hkSetTimeout(back, Duration duration) {
  Timer(duration, back);
}

// 代码块拦截
void hkTryCatch(Function? f) {
  try {
    f?.call();
  } catch (e, stack) {
    Log.e('$e');
    Log.e('$stack');
  }
}

class Utils {

  /// 设置状态栏和导航栏
  static setSystemUi() {
    if (Platform.isAndroid) {
      SystemUiOverlayStyle systemUiOverlayStyle = const SystemUiOverlayStyle(
          statusBarColor: Colors.transparent,
          statusBarBrightness: Brightness.light,
          statusBarIconBrightness: Brightness.dark,
          systemNavigationBarDividerColor: Colors.transparent,
          systemNavigationBarColor: Colors.white,
          systemNavigationBarIconBrightness: Brightness.dark);
      SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
    }
  }

  /// throttle节流
  /// 让函数有节制地执行，而不是毫无节制的触发一次就执行一次。
  /// 什么叫有节制呢？就是在一段时间内，只执行一次。
  /// [func]: 要执行的方法
  // ignore: prefer_typing_uninitialized_variables
  static var lastPopTime;

  static void throttle({required Future Function() func, int seconds = 3}) {
    // 防重复提交
    if (lastPopTime == null ||
        DateTime.now().difference(lastPopTime) > Duration(seconds: seconds)) {
      lastPopTime = DateTime.now();
      func();
      print("允许点击");
    } else {
      print("请勿重复点击！");
    }
  }

  /*
  使用案例：
  Utils.throttle(
        func: () async {
          overMod.isrunChange(true);
          postHttp('v1/logout', {}, (res) {
            if (res['code'] == 200) {
              removeKey('Authorization');
              if (!readKey('Authorization')) {
                Get.offAllNamed('/login');
              }
              overMod.isrunChange(false);
            }
            ShowMsg('${res['message']}');
          }, showLoading: true, isLogout: true);
        });
  */

  /// 随机色设置
  static getRandomColor() {
    return Color.fromARGB(255, Random.secure().nextInt(255),
        Random.secure().nextInt(255), Random.secure().nextInt(255));
  }
}
